"""
采集百度图库素材的图片
"""

from tools.requestTools import Request
from tools.loggingConfig import logger

# 初始化请求对象
request = Request()


def getImages(word, imgNum):
    """
    采集百度图库的图片
    以标题作为关键字爬取百度图库图片
    """
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
    }
    params = {
        'tn': 'resultjson_com',
        'ipn': 'rj',
        'ct': 201326592,
        'is': '',
        'fp': 'result',
        'queryWord': word,
        'cl': 2,
        'lm': -1,
        'ie': 'utf-8',
        'oe': 'utf-8',
        'adpicid': '',
        'st': -1,
        'z': '',
        'ic': '',
        'hd': '',
        'latest': '',
        'copyright': '',
        'word': word,
        's': '',
        'se': '',
        'tab': '',
        'width': '',
        'height': '',
        'face': 0,
        'istype': 2,
        'qc': '',
        'nc': '1',
        'fr': '',
        'expermode': '',
        'force': '',
        'cg': '',  # 这个参数没公开，但是不可少
        'pn': 30,  # 显示：30-60-90
        'rn': '30',  # 每页显示 30 条
        'gsm': '1e',
        '1618827096642': ''
    }
    url = f"https://image.baidu.com/search/acjson?"
    response = request.get(url=url, headers=headers, params=params)
    data = response.json()["data"][:imgNum]
    img_urls = [img["middleURL"] for img in data]
    if len(img_urls) < imgNum:
        logger.error("图片采集数量不够")
        raise Exception("图片采集数量不够")
    image_byte_list = []
    for imgUrl in img_urls:
        response = request.get(url=imgUrl)
        image_byte_list.append(response.content)
    return image_byte_list

